//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.dao.UserInfoDao;
import com.wsd.smartcarwasher.domain.Coupon;
import com.wsd.smartcarwasher.domain.Pagination;
import com.wsd.smartcarwasher.domain.UserCoupon;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.util.PageInfo;
import com.wsd.smartcarwasher.util.RandomUtils;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class UserInfoService {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);
    @Resource
    private RedisService redisService;
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserCouponService userCouponService;
    @Autowired(required = false)
    @Lazy
    private CouponService couponService;

    public UserInfoService() {
    }



    public UserInfo findByUsername(String username) {
        UserInfo userInfo = this.userInfoDao.findByUsername(username);
        userInfo.setNickname("张三");
        userInfo.setState(101);
        userInfo.setRole("admin");
        return userInfo;
    }

    public UserInfo findByOpenId(String openId) {
        return this.userInfoDao.findByOpenId(openId);
    }

    public UserInfo addUserInfo(UserInfo userInfo) {
        String salt = System.currentTimeMillis() + "";
        userInfo.setSalt(salt);
        String password = (new SimpleHash("MD5", userInfo.getPassword(), userInfo.getSalt(), 2)).toString();
        userInfo.setPassword(password);
        int result = this.userInfoDao.addUserInfo(userInfo);
        return result != 1 ? null : userInfo;
    }

    public UserInfo getCurrentUserInfo(String sessionId) {
        String cacheValue = (String)this.redisService.get(sessionId);
        if (cacheValue.contains("---")) {
            String openId = cacheValue.split("---")[0];
            return this.findByOpenId(openId);
        } else {
            return this.userInfoDao.findByUserId(cacheValue);
        }
    }

    public int updateUserWxCodeUrl(UserInfo userInfo) {
        return userInfo.getWxCodeUrl() == null ? 0 : this.userInfoDao.updateUserWxCodeUrl(userInfo);
    }





    public void addUserInfo(String openId,String unionId) {
        UserInfo userInfo = this.userInfoDao.findByOpenId(openId);
        if (userInfo == null) {
            UserInfo user = new UserInfo();
            user.setUserId(this.generateUserId());
            user.setOpenid(openId);
            user.setUnionId(unionId);
            user.setState(0);
            user.setRegisterTime(new Date());
            user.setBalance(BigDecimal.ZERO);
            int changeRow = this.userInfoDao.addUserInfo(user);
            if (changeRow == 0) {
                logger.error("添加用户信息失败");
            }
        }else{
            try{
                if(StringUtil.isNullOrEmpty(userInfo.getUnionId()))
                {
                    userInfo.setUnionId(unionId);
                    int changeRow = this.userInfoDao.updateUserUnionId(userInfo);
                    if (changeRow == 0) {
                        logger.error("更新用户信息失败");
                    }
                }
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }



    }






    private synchronized String generateUserId() {
        String userId = RandomUtils.generateString(10);

        for(List userIds = this.getAllUserId(); userIds.contains(userId); userId = RandomUtils.generateString(10)) {
        }

        return userId;
    }

    private List<String> getAllUserId() {
        List<String> userIds = this.userInfoDao.getAllUserId();
        return CollectionUtils.isEmpty(userIds) ? Collections.emptyList() : userIds;
    }

    public List<UserInfo> queryUserWithRole(String role) {
        return this.userInfoDao.queryUserWithRole(role);
    }

    //========================= new lyj================================
    //新增带手机号

    @Resource
    private SysDicService sysDicService;
    public void addUserInfoLyj(UserInfo  user) {
        if(null!= user.getFromId()){
            Coupon coupon  = new Coupon();
            coupon.setStatus(1);
            coupon.setCouponName("用户分享卷");
            coupon.setCouponRate( new BigDecimal(sysDicService.getByCode(1001).get(0).getValue()));
            coupon.setTime(new Date());
            coupon.setUseNum(1);
            coupon.setValidDate(Integer.parseInt(sysDicService.getByCode(1004).get(0).getValue()));
            coupon.setCouponNum(2);
            coupon.setType(2);
            coupon.setAvailableMachines("ALLMACHINS");
            //coupon.setIsMultiple(1);
            int rows = couponService.addCoupon(coupon);
            if(rows<1){
                logger.info("生成分享优惠卷失败！！");
                return;
            };
            //coupon = couponService.getCouponsByCode(coupon.getCouponCode());
            //Coupon coupon = couponService.getCouponsByNewB();
            if(coupon==null){
                logger.info("没有找到要分享的优惠卷！！");
                return;
            }
            //给ａ加
            UserCoupon userCoupon = userCouponService.addUserCouponByShare(user.getFromId(),coupon,1);

            if (null ==userCoupon) {
                //return ReturnUtil.Error(ResultState.ADD_COUPON_FAIL.getMsg());
                logger.error("添加用户"+user.getFromId()+" 添加优惠卷信息失败");
            }else{
                logger.info(user.getFromId()+" 添加分享优惠卷信息成功");
            }

            //给ｂ加
            userCoupon = userCouponService.addUserCouponByShare(user.getUserId(),coupon,0);
            if (null ==userCoupon) {
                logger.error("添加用户"+user.getUserId()+" 添加优惠卷信息失败");
            }else{
                logger.info(user.getUserId()+" 添加分享优惠卷信息成功");
            }
        }
    }
    //以前存在用户 现在更新手机号
    public int updateUserMobileByOpenid(UserInfo  user) {
        return this.userInfoDao.updateUserMobileByOpenid(user);
    }

    public PageInfo<UserInfo> getAllUserInfo(int page, int pageSize, String mobile) {
        mobile =null==mobile?"":mobile;
        PageHelper.startPage(page,pageSize);
        List<UserInfo>  ls=userInfoDao.getAllUserInfo(mobile);
        return new PageInfo<UserInfo>(ls);
    }

    public int updateUser(UserInfo user) {

        try{
            int rows = userInfoDao.updateUserMobileByOpenid(user);
            return rows;
        }catch (Exception e){
            e.printStackTrace();
            logger.info("修改用户登陆最后时间失败");
        }
        return 0;
    }

    public  UserInfo findById(String userId){
        return this.userInfoDao.findByUserId(userId);
    }

    public UserInfo findByMobile(String mobile) {
        return this.userInfoDao.findByMobile(mobile);
    }
}


/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.dao.UserInfoDao;
import com.wsd.smartcarwasher.domain.UserInfo;
import com.wsd.smartcarwasher.util.RandomUtils;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoService {
    private static final Logger logger = LoggerFactory.getLogger(UserInfoService.class);

    @Resource
    private RedisService redisService;

    @Resource
    private UserInfoDao userInfoDao;

    public UserInfo findByUsername(String username) {
        UserInfo userInfo = userInfoDao.findByUsername(username);
        userInfo.setNickname("张三");

        userInfo.setState(101);

        userInfo.setRole("admin");

        return userInfo;
    }

    public UserInfo findByOpenId(String openId) {
        return userInfoDao.findByOpenId(openId);
    }

    //根据账号密码登录
    public ModelMap loginByPassword(UserInfo userInfo) {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> resultMap = new HashMap<>();

        try {
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword());
                token.setRememberMe(true);
                subject.login(token);
            }
            resultMap.put("token", subject.getSession().getId());
            resultMap.put("userInfo", userInfo);
            redisService.put(subject.getSession().getId().toString(), userInfo.getUserId().toString(), 9600);
        } catch (IncorrectCredentialsException e) {
            return ReturnUtil.Error("密码错误");
        } catch (LockedAccountException e) {
            return ReturnUtil.Error("用户状态异常");
        } catch (AuthenticationException e) {
            return ReturnUtil.Error("用户不存在");
        } catch (Exception e) {
            logger.error("登录失败", e.getMessage());
            return ReturnUtil.Error("登录失败");
        }
        return ReturnUtil.Success("登陆成功", resultMap);
    }

    public UserInfo addUserInfo(UserInfo userInfo) {
        String salt = System.currentTimeMillis() + "";
        userInfo.setSalt(salt);
        //加密密码
        String password = new SimpleHash(Global.HASH_ALGORITHM_NAME, userInfo.getPassword(), userInfo.getSalt(), Global.HASH_ITERATIONS).toString();
        userInfo.setPassword(password);
        int result = userInfoDao.addUserInfo(userInfo);

        if (result != 1) {
            return null;
        }
        return userInfo;
    }

    public UserInfo getCurrentUserInfo(String sessionId) {
        String cacheValue = (String) redisService.get(sessionId);
        if (cacheValue.contains("---")) {
            String openId = cacheValue.split("---")[0];
            return findByOpenId(openId);
        } else {
            return userInfoDao.findByUserId(cacheValue);
        }
    }

    public int updateUserWxCodeUrl(UserInfo userInfo) {
        if (userInfo.getWxCodeUrl() == null) {
            return 0;
        }
        return userInfoDao.updateUserWxCodeUrl(userInfo);
    }

    public void addUserInfo(String openId) {
        UserInfo userInfo = userInfoDao.findByOpenId(openId);
        if (userInfo == null) {
            UserInfo user = new UserInfo();
            user.setUserId(generateUserId());
            user.setOpenid(openId);
            int changeRow = userInfoDao.addUserInfo(user);
            if (changeRow == 0) {
                logger.error("添加用户信息失败");
            }
        }
    }

    private synchronized String generateUserId() {
        String userId = RandomUtils.generateString(10);
        List<String> userIds = getAllUserId();
        while (userIds.contains(userId)) {
            userId = RandomUtils.generateString(10);
        }
        return userId;
    }

    private List<String> getAllUserId() {
        List<String> userIds = userInfoDao.getAllUserId();
        if (CollectionUtils.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        return userIds;
    }

    public List<UserInfo> queryUserWithRole(String role) {
        return userInfoDao.queryUserWithRole(role);
    }
}
*/
